import fs from 'fs'

export type Doc = {
  slug: string;
  meta: Record<string, unknown>;
  content: string;
};
import path from 'path'
import matter from 'gray-matter'

const docsDirectory = path.join(process.cwd(), 'src', 'app', 'docs')

export function getDocBySlug(slug: string) {
  const realSlug = slug.replace(/\.mdx$/, '')
  const fullPath = path.join(docsDirectory, `${realSlug}.mdx`)
  const fileContents = fs.readFileSync(fullPath, 'utf8')
  const { data, content } = matter(fileContents)

  return { slug: realSlug, meta: data, content }
}

export function getAllDocs() {
  const fileNames = fs.readdirSync(docsDirectory)
  const mdxFiles = fileNames.filter((fileName) => {
    const fullPath = path.join(docsDirectory, fileName)
    return fs.statSync(fullPath).isFile() && fileName.endsWith('.mdx')
  })
  const docs = mdxFiles.map((fileName) => {
    return getDocBySlug(fileName)
  })
  return docs
}